#!/usr/bin/env bash
set -eo pipefail

BIN_URL="https://raw.githubusercontent.com/matter-labs/zksync-era/main/zkstack_cli/zkstackup/zkstackup"

BIN_DIR="$HOME/.local/bin"
BIN_PATH="$BIN_DIR/zkstackup"

main() {
  parse_args "$@"

  mkdir -p "$BIN_DIR"

  if [ -n "$ZKSTACKUP_PATH" ]; then
    cp -r "$ZKSTACKUP_PATH" "$BIN_DIR"
  else
    curl -sSfL "$BIN_URL" -o "$BIN_PATH"
  fi

  chmod +x "$BIN_PATH"
  echo "zkstackup: successfully installed in ${BIN_DIR}."

  add_bin_folder_to_path
}

add_bin_folder_to_path() {
  if [[ ":$PATH:" == *":${BIN_DIR}:"* ]]; then
    echo "zkstackup: found ${BIN_DIR} in PATH"
    exit 0
  fi

  case $SHELL in
  */zsh)
    PROFILE="${ZDOTDIR-"$HOME"}/.zshenv"
    ;;
  */bash)
    PROFILE="$HOME/.bashrc"
    ;;
  */fish)
    PROFILE="$HOME/.config/fish/config.fish"
    ;;
  */ash)
    PROFILE="$HOME/.profile"
    ;;
  *)
    echo "zkstackup: could not detect shell, manually add ${BIN_DIR} to your PATH."
    exit 1
    ;;
  esac

  if [[ ! -f "$PROFILE" ]]; then
    echo "zkstackup: Profile file $PROFILE does not exist, creating it."
    touch "$PROFILE"
  fi

  if [[ "$SHELL" == *"/fish"* ]]; then
    echo -e "\n# Added by zkstackup\nfish_add_path -a $BIN_DIR" >>"$PROFILE"
    echo "zkstackup: Added $BIN_DIR to PATH in $PROFILE using fish_add_path."
  else
    echo -e "\n# Added by zkstackup\nexport PATH=\"\$PATH:$BIN_DIR\"" >>"$PROFILE"
    echo "zkstackup: Added $BIN_DIR to PATH in $PROFILE."
  fi

  echo
  echo "Added zkstackup to PATH."
  echo "Run 'source $PROFILE' or start a new terminal session to use zkstackup."
  echo "Then run 'zkstackup' to install ZK Stack CLI."
}

parse_args() {
  while [[ $# -gt 0 ]]; do
    case $1 in
    --)
      shift
      break
      ;;
    -p | --path)
      shift
      ZKSTACKUP_PATH=$1
      ;;
    -l | --local)
      ZKSTACKUP_PATH="./"
      ;;
    -g | --global)
      BIN_DIR="/usr/local/bin"
      BIN_PATH="$BIN_DIR/zkstackup"
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    *)
      err "Unknown argument: $1"
      usage
      exit 1
      ;;
    esac
    shift
  done
}


usage() {
  cat <<EOF
Install script for zkstackup.

Usage: $(basename "$0") [OPTIONS]

Options:
  -p, --path <path>         Specify a local path to install zkstackup from.
  -l, --local               Install zkstackup from the current directory.
  -g, --global              Install zkstackup for all users.
  -h, --help                Show this help message and exit.

Examples:
  $(basename "$0") --path /path/to/zkstackup
EOF
}

main "$@"
